package com.example.color_test.test;

import com.example.color_test.entity.TestResult;

import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.concurrent.FutureTask;

import javax.imageio.ImageIO;


public class Calculate{

    public static String calculateGreen(String image) throws Exception {
        File file = new File(image);
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int width = bi.getWidth();
        int height = bi.getHeight();
        int minx = bi.getMinX();
        int miny = bi.getMinY();



        // 平分任务，使用 FutureTask 包装，获取返回值。
        FutureTask<Long> fTask1 = new FutureTask<>(
                new CalculateTask(minx, miny, width / 2, height, bi));
        FutureTask<Long> fTask2 = new FutureTask<>(
                new CalculateTask(width / 2 + 1, miny, width, height, bi));
        new Thread(fTask1).start();
        new Thread(fTask2).start();

        long res1 = fTask1.get();
        long res2 = fTask2.get();

        //由主线程汇总
        long totalGreenPixel = res1 + res2;
        long totalPixelNumber = width * height;

        double greenPixelProportion = (double) totalGreenPixel / totalPixelNumber;
        return translateDoubleIntoPercent(greenPixelProportion);
    }

    /**
     * 将浮点数转换为百分制
     * @param d
     * @return
     */
    public static String translateDoubleIntoPercent(double d) {
        BigDecimal bDecimal = new BigDecimal(d);
        bDecimal = bDecimal.setScale(4, BigDecimal.ROUND_HALF_UP);
        DecimalFormat dFormat = new DecimalFormat("0.00%");
        String result = dFormat.format(bDecimal.doubleValue());
        return result;
    }

    public static TestResult getTest(String path){
        TestResult testResult = new TestResult();
        long start = System.currentTimeMillis();
        String probability = null;
        try {
            testResult.setPercent(calculateGreen(path));
            probability = testResult.getPercent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long time = System.currentTimeMillis() - start;
        testResult.setTestTime(time +"ms");
        System.out.println("hsv提取绿视率:" + probability + ",耗时：" + time + "ms");
        return testResult;
    }

    public static void main(String[] args) throws IOException {

        long start = System.currentTimeMillis();
        String probability = null;
        try {
            probability = calculateGreen("F:\\Project\\myProject\\getColor\\test_image\\1.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        long time = System.currentTimeMillis() - start;

        System.out.println("hsv提取绿视率:" + probability + ",耗时：" + time + "ms");


    }


}